package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.face.AipFaceTemplate;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.Log;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//spring的
@Service
public class UserManager {

    @Autowired
    private SmsTemplate smsTemplate;

    //dubbo的
    @Reference
    private UserService userService;

    @Reference
    private UserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplatel;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //查找用户手机号
    public String findPhone() {
        Long userId = UserHolder.get().getId();

        User user = userService.findPhone(userId);

        return user.getPhone();
    }

    //修改手机号 - 2 校验验证码
    public Map<String, Boolean> checkVerificationCode(String verificationCode) {
        //获取手机验证码
        String code = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + findPhone());

        Boolean verification;
        Map<String, Boolean> resultMap = new HashMap<>();
        //判断是否相同
        if (StringUtils.equals(verificationCode, code)) {
            verification = true;
            resultMap.put("verification", verification);
            return resultMap;
        } else {
            verification = false;
            resultMap.put("verification", verification);
            return resultMap;
        }
    }

    //修改手机号 - 3 保存
    public void saveUserPhone(String phone) {
        //查找到用户的信息
        User user = userService.findByPhone(findPhone());

        Map<String, Object> mapOldUser = new HashMap<>();
        mapOldUser.put("id",user.getId());
        mapOldUser.put("phone",user.getPhone());

        String oldUserToken = JwtUtil.createToken(mapOldUser);
        String s = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + oldUserToken);

        user.setPhone(phone);
        userService.update(user);

        if (s != null){
            //制作Token
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("phone", user.getPhone());
            System.out.println("new "+user.getPhone());

            //获取token 存入Redis中
            String token = JwtUtil.createToken(map);
            stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, user.getPhone() + "", Duration.ofDays(30));

            //验证成功，删除验证码
            stringRedisTemplate.delete(ConstantUtil.SMS_CODE + findPhone());

            //从redis中删除原本用户
            stringRedisTemplate.delete(ConstantUtil.USER_TOKEN+oldUserToken);
        }



        //老用户
        Boolean isNew = false;
        //设置登录type
        String type = "0101";

        Log log = new Log();
        log.setType(type);//操作类型
        log.setUserId(user.getId());//用户id
        log.setLogTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));//操作日期
        log.setPlace("北京顺义");//mongo中的location中有,下课自己完成
        log.setEquipment("华为19");//设备名称
        rocketMQTemplate.convertAndSend("tanhua-log", log);
    }



    //保存用户,返回主键
    public Long save(User user) {
        //密码加密
        String md5Password = SecureUtil.md5(user.getPassword());
        user.setPassword(md5Password);

        return userService.save(user);
    }

    //根据手机号查询用户
    public User findByPhone(String phone) {
        return userService.findByPhone(phone);
    }

    //发送手机验证码
    public void sendSmsCode(String phone) {
        String numbers = RandomUtil.randomNumbers(6);

        //smsTemplate.sendSms(phone,numbers);
        System.out.println(numbers);

        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone,numbers, Duration.ofMinutes(5));

    }


    //检验手机验证码
    public Map<String,Object> regAndLogin(String phone, String verificationCode) {

        Boolean isNew = null;
        String type = "0101";//登录

        String code = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        if (!StringUtils.equals(verificationCode, code)) {
            throw new RuntimeException("验证码有误！");
        }

        //验证成功，删除验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + phone);

        User user = userService.findByPhone(phone);
        if (user != null) {
            //老用户
            System.out.println("老用户:"+user);
            isNew = false;
        } else {
            //新用户
            user = new User();
            user.setPhone(phone);
            String password = RandomUtil.randomNumbers(6);
            password = SecureUtil.md5(password);
            user.setPassword(password);
            Long id = userService.save(user);
            user.setId(id);

            //向环信发送新用户id
            huanXinTemplate.register(user.getId());

            System.out.println("新用户:"+user);
            isNew = true;
            type = "0102";//注册
        }

        Log log = new Log();
        log.setType(type);//操作类型
        log.setUserId(user.getId());//用户id
        log.setLogTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));//操作日期
        log.setPlace("北京顺义");//mongo中的location中有,下课自己完成
        log.setEquipment("华为19");//设备名称
        rocketMQTemplate.convertAndSend("tanhua-log", log);

        //制作Token
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("phone", user.getPhone());

        String token = JwtUtil.createToken(map);

        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN+token,user.getPhone()+"",Duration.ofDays(30));
        stringRedisTemplate.opsForValue().set("sound_time" + user.getId(),10 + "",Duration.ofDays(1));

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        resultMap.put("isNew", isNew);
        return resultMap;
    }

    //完善个人基本信息
    public void saveUserBaseInfo(UserInfo userInfo) {
        userInfoService.save(userInfo);
    }

    //完善个人头像信息
    public void saveUserHeadInfo(Long id, MultipartFile headPhoto) throws IOException {

        boolean detect = aipFaceTemplatel.detect(headPhoto.getBytes());
        if (!detect) {
            throw new RuntimeException("图片审核失败！");
        }

        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(upload);
        userInfo.setCoverPic(upload);

        userInfoService.update(userInfo);
    }

    //查询个人信息
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoService.findById(id);
        System.out.println(userInfo);

        //封装
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo,userInfoVo);

        userInfoVo.setAge(userInfo.getAge() + "");

        return userInfoVo;
    }

    //更新个人信息
    public void updateUserBaseInfo(UserInfo userInfo) {
        userInfoService.update(userInfo);
    }
}
